<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>v-for&排序</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script type="text/javascript" src="../assets/js/vue.js"></script>
</head>

<body>
    <h1>v-for</h1>
    <a href="../index.html">返回</a>
    <hr/>
    <div id="app">

        <ul>
            <li v-for="item in setItems">{{item}}</li>
        </ul>
        <hr/>
        <ul>
            <li v-for="(item,index) in setStudents">
                {{index}}. {{item.name}}排序{{item.index}}</li>
        </ul>


    </div>

    <script>
        var app = new Vue({
            el: "#app",
            data: {
                items: [20, 14, 23, 22, 48, 289, 33, 66, 120],
                students: [{
                    name: 'C#',
                    index: 8
                }, {
                    name: 'Java',
                    index: 1
                }, {
                    name: 'Python',
                    index: 6
                }, {
                    name: 'vue',
                    index: 3
                }]
            },
            computed: {
                setItems: function() {
                    //return [1, 2, 3, 4, 5, 6, 6]]
                    //使用this.items.sort();进行排序 无效
                    var _n = this.items.sort(function(a, b) {
                        return a - b; //a-b 正序，b-a倒序
                    });
                    console.log(_n);
                    return _n;
                },
                setStudents: function() {
                    return sortStudents(this.students, 'index');
                }
            }
        })

        function sortStudents(stu, key) {
            return stu.sort(function(a, b) {
                var x = a[key];
                var y = b[key];
                return ((x < y) ? -1 : ((x > y) ? 1 : 0));
            })
        }
    </script>
</body>

</html>